package com.example.voucher.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.example.voucher.biz.VoucherBiz;
import com.example.voucher.common.TenantCodeThreadLocal;
import com.example.voucher.contract.VoucherItemCapable;
import com.example.voucher.entity.Voucher;
import com.example.voucher.enums.VoucherTypeEnum;
import com.example.voucher.extension.ExtensionExecutor;
import com.example.voucher.extension.ExtensionImpl;
import com.example.voucher.service.PurchaseInvoiceQueryService;
import com.example.voucher.service.SalesInvoiceQueryService;
import com.example.voucher.service.VoucherItemConvertPostService;
import com.example.voucher.service.VoucherItemConvertService;
import com.example.voucher.service.VoucherService;
import com.google.common.collect.Lists;

@ExtensionImpl
public class VoucherServiceImpl implements VoucherService {

    @Autowired
    private VoucherBiz voucherBiz;
    @Autowired
    private ExtensionExecutor extensionExecutor;
    @Autowired
    private VoucherItemConvertService convertService;

    @Override
    public void genEasVoucher(final List<Long> pkidList, VoucherTypeEnum voucherType) {
        // 1.获取原始数据
        // 通过统一的数据结构VoucherItemCapable，隔离不同场景凭证数据来源的差异
        List<VoucherItemCapable> srcList = Lists.newArrayList();
        // 根据租户 和 voucherType 获取数据源的扩展点编号
        String tenantCode = TenantCodeThreadLocal.getTenantCode();
        switch (voucherType) {
            case PurchaseInvoice:
                srcList.addAll(extensionExecutor.executeByTenantCode(PurchaseInvoiceQueryService.class, tenantCode,
                    t -> t.queryVoucherItem(pkidList)));
                break;
            case SaleInvoice:
                srcList.addAll(extensionExecutor.executeByTenantCode(SalesInvoiceQueryService.class, tenantCode,
                    t -> t.queryVoucherItem(pkidList)));
                break;
            default:
                break;
        }

        // 2.List<VoucherItemAccessor>--->List<Voucher>
        List<Voucher> voucherList = convertService.convert(srcList);
        // List<Voucher> voucherList = extensionExecutor.executeVoidByTenantCode(VoucherItemConvertService.class, tenantCode, t -> t.convert(fromList));
        
        // 转换的后置处理
        extensionExecutor.executeVoidByTenantCode(VoucherItemConvertPostService.class, tenantCode, t -> t.convertPost(voucherList));
        
        // 3.写数据库
        voucherBiz.saveBatch(voucherList, 500);
    }

}
